package com.example.android.commitcontent.ime.keyboard.managers;

import android.text.TextUtils;
import android.util.Log;

import com.example.android.commitcontent.ime.beans.HanZiWord;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;
import com.example.android.commitcontent.ime.beans.HanZiCharacter;

import java.util.ArrayList;
import java.util.List;

/**
 * 词组生成工具类
 */
public class PinYinWordsBuilder {
    private PinYinWordsBuilder() {
    }

    public static PinYinWordsBuilder instance() {
        return new PinYinWordsBuilder();
    }

    List<HanZiCharacter> mHanZiCharacters = new ArrayList<>();

    public void append(HanZiCharacter hanZiCharacter) {
        if (hanZiCharacter.isWord()) {
            String[] pinyins = hanZiCharacter.pinyin.split(",");
            for (int i = 0; i < pinyins.length; i++) {
                mHanZiCharacters.add(new HanZiCharacter(String.valueOf(hanZiCharacter.hanzi.charAt(i)), pinyins[i]));
            }
        } else {
            mHanZiCharacters.add(hanZiCharacter);
        }
    }

    public void clear() {
        mHanZiCharacters.clear();
    }

    public int length() {
        return mHanZiCharacters.size();
    }

    public void buildNewWord() {
        if (mHanZiCharacters.size() <= 1) {
            this.clear();
            return;
        }
        StringBuilder word = new StringBuilder();
        StringBuilder pinyin = new StringBuilder();
        StringBuilder short_pinyin = new StringBuilder();
        for (HanZiCharacter hanZiCharacter : mHanZiCharacters) {
            word.append(hanZiCharacter.hanzi);
            if (TextUtils.isEmpty(hanZiCharacter.pinyin)) continue;
            pinyin.append(hanZiCharacter.pinyin);
            pinyin.append(",");
            short_pinyin.append(hanZiCharacter.pinyin.charAt(0));
            short_pinyin.append(",");
        }
        this.clear();
        if (pinyin.length() > 0) {
            pinyin.delete(pinyin.length() - 1, pinyin.length());
            short_pinyin.delete(short_pinyin.length() - 1, short_pinyin.length());
        }
        saveWord(new HanZiWord(word.toString(), pinyin.toString(), short_pinyin.toString()));
        Log.e("your input", String.format("%s       %s        %s", word, pinyin, short_pinyin));
    }

    private void saveWord(HanZiWord hanZiWord) {
        HanZiStatisticsDataBaseHelper.intance(null).wordsRepeatCount(hanZiWord);
    }
}
